/**
 * 
 */
package org.tcp.client.pool;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;

/**
 * @author kucheng.liao@autonavi.com
 * @Date Sep 19, 2014
 */
public class TcpConnection implements ITcpConnection {

	private Socket socket;

	private Pool pool;

	int heatTestTime;

	private Date lastUseDate = new Date();

	public TcpConnection(String ip, int port, Pool pool) throws UnknownHostException, IOException {
		this.socket = new Socket(ip, port);
		socket.setKeepAlive(true);
		socket.setTcpNoDelay(true);
		this.pool = pool;

	}

	public OutputStream getOutputStream() throws IOException {
		return socket.getOutputStream();
	}

	public InputStream getInputStream() throws IOException {
		return socket.getInputStream();
	}

	public void close() {
		lastUseDate = new Date();
		heatTestTime = 0;
		pool.push(this);
	}

	public Date getLastUseDate() {
		return lastUseDate;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tcp.client.pool.ITcpConnection#destory()
	 */
	public void destory() throws IOException {
		if (null != socket && socket.isConnected()) {
			socket.close();
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tcp.client.pool.ITcpConnection#pool()
	 */
	public Pool pool() {
		return this.pool;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tcp.client.pool.ITcpConnection#getHeatTime()
	 */
	public int getHeatTestTime() {
		return heatTestTime;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tcp.client.pool.ITcpConnection#setHeatTestTime(int)
	 */
	public void addHeatTestTime(int time) {
		heatTestTime += time;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tcp.client.pool.ITcpConnection#setLastUserDate(java.util.Date)
	 */
	public void setLastUserDate(Date date) {
		this.lastUseDate = date;
	}
}
